<template>
  <div class="main-box">
    <TreeFilter
      label="name"
      title="部门列表"
      :data="treeFilterData"
      :default-value="initParam.departmentId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        row-key="id"
        :indent="20"
        :columns="columns"
        :request-api="getTableList"
        :request-auto="false"
        :init-param="initParam"
        :data-callback="dataCallback"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
      >
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link @click="selecrUser(scope.row)">
            <el-icon style="vertical-align: middle"><Select></Select></el-icon>
            选择
          </el-button>
        </template>
      </ProTable>
    </div>
  </div>
</template>

<script setup lang="tsx" name="treeProTable">
import { onMounted, reactive, ref, defineComponent } from "vue";
import { User, OrgManager } from "@/api/interface";
import { genderType } from "@/utils/dict";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage, ElNotification } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getUserTreeList, deleteUser, editUser, addUser, getUserStatus, getUserDepartment } from "@/api/modules/user";
import { findUserTreeList, findUser } from "@/api/modules/jggl";
onMounted(() => {
  getTreeFilter();
  // ElNotification({
  //   title: "温馨提示",
  //   message: "该页面 ProTable 数据不会自动请求，需等待 treeFilter 数据请求完成之后，才会触发表格请求。",
  //   type: "info",
  //   duration: 10000
  // });
  // setTimeout(() => {
  //   ElNotification({
  //     title: "温馨提示",
  //     message: "该页面 ProTable 性别搜索框为远程数据搜索，详情可查看代码。",
  //     type: "info",
  //     duration: 10000
  //   });
  // }, 0);
  initParam.departmentId = fatherElement.father.orgNo;
});

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ departmentId: "", companyNo: 1, belongsGroupIds: "", page: 1, rows: 10, orgType: "" });

// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.departmentId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const data = await getUserDepartment();
  // 使用traverseTree遍历树
  traverseTree(data[0], node => {
    node.id = node.attr.orgName;
    node.name = node.attr.orgName;
  });
  treeFilterData.value = data;
  initParam.departmentId = data[0].attr.orgNo;
};

// 树形筛选切换
const changeTreeFilter = (val: any) => {
  if (val instanceof Array) {
    return;
  }
  // 使用traverseTree遍历树
  traverseTree(treeFilterData.value[0], node => {
    if (node.attr.orgName == val) {
      if (node.attr.orgType == "company") {
        initParam.orgType = "";
      } else if (node.attr.orgType == "innerPanel") {
        initParam.orgType = "allInner";
      } else if (node.attr.orgType == "servicePanel") {
        initParam.orgType = "allService";
      } else {
        initParam.orgType = "";
      }
      initParam.departmentId = node.attr.orgNo;
      // initParam.companyNo = node.attr.orgNo;
      initParam.belongsGroupIds = node.attr.orgNo;
    }
  });

  proTable.value!.pageable.pageNum = 1;
  initParam.page = proTable.value!.pageable.pageNum;
  initParam.rows = proTable.value!.pageable.pageSize;
  //initParam.departmentId = val;
};

// 模拟远程加载性别搜索框数据
const loading = ref(false);
const filterGenderEnum = ref<typeof genderType>([]);
const remoteMethod = (query: string) => {
  filterGenderEnum.value = [];
  if (!query) return;
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    filterGenderEnum.value = genderType.filter(item => item.label.includes(query));
  }, 500);
};

// 表格配置项
const columns = reactive<ColumnProps<OrgManager.ResOrgList>[]>([
  // { type: "index", label: "#", width: 80 },
  { prop: "loginName", label: "登录名", search: { el: "input" } },
  { prop: "fullName", label: "用户名称", width: 120, search: { el: "input" } },
  {
    prop: "sex",
    label: "用户状态",
    sortable: true,
    isFilterEnum: false,
    enum: filterGenderEnum,
    // search: {
    //   el: "select",
    //   props: { placeholder: "请输入性别查询", filterable: true, remote: true, reserveKeyword: true, loading, remoteMethod }
    // },
    render: scope => <>{scope.row.userState === true ? "值班中" : "休假中"}</>
  },
  // { prop: "moblie", label: "手机号" },
  // { prop: "email", label: "邮箱" },
  // { prop: "orgName", label: "居住地址" },
  // {
  //   prop: "status",
  //   label: "用户状态",
  //   sortable: true,
  //   tag: true,
  //   enum: getUserStatus,
  //   search: { el: "tree-select" },
  //   fieldNames: { label: "userLabel", value: "userStatus" }
  // },
  // { prop: "createTime", label: "创建时间", width: 180 },
  { prop: "operation", label: "操作", width: 100, fixed: "right" }
]);

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(deleteUser, { id: [params.id] }, `删除【${params.username}】用户`);
  proTable.value?.getTableList();
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "userId";
  newParams.sord = "desc";

  return findUser(newParams, "userQueryDto", ["_search", "sidx", "sord", "page", "rows"]);
};

const selfEmit = defineEmits(["sendData"]);
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const selecrUser = (row: Partial<OrgManager.ResOrgList> = {}) => {
  //回调数据给父组件
  selfEmit("sendData", row);
};

interface TreeNode {
  value: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}

// 通过defineProps接收父组件的值
const fatherElement = defineProps({
  // 接收传值   此处的father就是父组件的自定义名称
  father: {
    type: Object, // 数据类型
    default() {
      return {};
    } // 未传值时的默认值
  }
});
// initParam.companyNo = fatherElement.father.orgNo;
initParam.departmentId = fatherElement.father.orgNo;
initParam.belongsGroupIds = fatherElement.father.orgNo;
</script>
